<script setup lang="ts">
import { ColumnHeightOutlined, PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons-vue'
import type { MenuProps, PaginationProps, TableProps } from 'ant-design-vue'
import {deleteSalesDetailInfo, getSalesDetailList, updateSalesInfoOnPurchase} from '@/api/sales/sales-list.ts'
import { SalesDetailModel, SalesDetailMess } from '@/api/sales/sales-list.ts'
// 移除 moment 依赖，统一使用 dayjs
import SalesAdd from './sales-add.vue'
import SalesDetail from './sales-detail.vue'

import { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
import { ref } from 'vue'

const value1 = ref<Dayjs>()

const salesStatusMap = {
  1: '暂存',
  2: '已保存',
  3: '作废',
}
const salesTypeMap = {
  1: '正常销售',
  2: '全额顶销',
  3: '部分顶销',
}
const message = useMessage()
const columns = shallowRef([
  {
    title: '销售单号',
    dataIndex: 'salesId',
  },
  {
    title: '销售类型',
    dataIndex: 'salesType',
  },
  {
    title: '销售自动总价',
    dataIndex: 'salesTotalPrice',
  },
  {
    title: '实际销售总金额',
    dataIndex: 'salesActualTotalPrice',
  },
  {
    title: '去零',
    dataIndex: 'salesTotal',
  },
  {
    title: '总计销售纯利润',
    dataIndex: 'salesPureProfit',
  },
  {
    title: '备注',
    dataIndex: 'salesRemarks',
  },

  {
    title: '销售订单状态',
    dataIndex: 'salesStatus',
  },
  {
    title: '销售人',
    dataIndex: 'salesPerson',
  },
  {
    title: '所属采购单',
    dataIndex: 'purchaseName',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 240,
  },
])
const loading = shallowRef(false)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: 100,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `总订单数：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
// 销售单数据集
const dataSource = shallowRef<SalesDetailModel[]>([])
// 搜索条件
const formModel = reactive<SalesDetailModel>({
  salesId: undefined,
})

const tableSize = ref<string[]>(['large'])
const sizeItems = ref<MenuProps['items']>([
  {
    key: 'large',
    label: '默认',
    title: '默认',
  },
  {
    key: 'middle',
    label: '中等',
    title: '中等',
  },
  {
    key: 'small',
    label: '紧凑',
    title: '紧凑',
  },
])
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getSalesDetailList({
      ...formModel,
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    })
    console.log('加载销售订单数据完成')
    console.log(data)
    dataSource.value = data?.list ?? []
    pagination.total = data?.count
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

async function onSearch() {
  pagination.current = 1
  await init()
}

async function onReset() {
  // 清空所有参数重新请求
  formModel.purchaseId = undefined
  await init()
}

// 依据采购单信息进行更新销售单中的各项内容
async function handleUpdate(record: SalesDetailModel) {
  const close = message.loading('依据采购单信息更新中......')
  try {
    console.log(record)
    const reqForm = ref<SalesDetailModel>({
      salesId: record.salesId,
    })
    const res = await updateSalesInfoOnPurchase(reqForm.value)
    if (res.code === 200){
      await init()
      message.success('更新完成')
    }else {
      message.error(res.msg)
    }
  }
  catch (e) {
    console.log(e)
  }
  finally {
    close()
  }
}

/**
 * 删除功能
 *  @param record
 *
 */
async function handleDelete(record: SalesDetailModel) {
  const close = message.loading('删除中......')
  try {
    console.log(record)
    const reqForm = ref<SalesDetailModel>({
      salesId: record.salesId,
    })
    const res = await deleteSalesDetailInfo(reqForm.value)
    if (res.code === 200){
      await init()
      message.success('删除成功')
    }else {
      message.error(res.msg)
    }
  }
  catch (e) {
    console.log(e)
  }
  finally {
    close()
  }
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

/**
 * 全选/反选事件
 *
 */

function handleCheckAllChange(e: any) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}

watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)

/**
 * 重置事件
 *
 */
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}

const salesAdd = ref<InstanceType<typeof SalesAdd>>()

// 进入添加销售单页面
async function handleAdd() {
  console.log('进入添加销售单页面')
  salesAdd.value?.open()
}

// 进入销售单编辑页面
async function handleEdit(record: SalesDetailModel) {
  // TODO 待补充仓库类型编号
  salesAdd.value?.open(record)
}

// 声明一个详情组件
const salesDetail = ref<InstanceType<typeof SalesDetail>>()
// 打开详情组件
async function handleDetail(record: SalesDetailModel) {
  salesDetail.value?.open(record)
}

/**
 * checkbox点击事件
 *
 */
function handleCheckChange(value: any) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}

function onCreateTimeChange(value: any) {
  return dayjs(value * 1000).format('YYYY-MM-DD')
}

function formatDifference(salesTotalPrice: number | undefined, salesActualTotalPrice: number | undefined): string {
  if (salesTotalPrice === undefined || salesActualTotalPrice === undefined) {
    return '0.00';
  }
  const difference = salesTotalPrice - salesActualTotalPrice;
  return parseFloat(difference.toFixed(2)).toString();
}

onMounted(() => {
  init()
})
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="4">
            <a-form-item name="purchaseId" label="销售单号">
              <a-input v-model:value="formModel.salesId" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-space flex justify-end w-full>
              <a-button :loading="loading" type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button :loading="loading" @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="销售记录">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            添加销售记录
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
          <a-tooltip title="列设置">
            <a-dropdown v-model:open="dropdownVisible" trigger="click">
              <SettingOutlined />
              <template #overlay>
                <a-card>
                  <template #title>
                    <a-checkbox v-model:checked="state.checkAll" :indeterminate="state.indeterminate" @change="handleCheckAllChange">
                      列选择
                    </a-checkbox>
                  </template>
                  <template #extra>
                    <a-button type="link" @click="handleResetChange">
                      重置
                    </a-button>
                  </template>
                  <a-checkbox-group v-model:value="state.checkList" :options="options" style="display: flex; flex-direction: column;" @change="handleCheckChange" />
                </a-card>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination" :size="tableSize[0] as TableProps['size']">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a c-error @click="handleDelete(scope?.record as SalesDetailModel)">
                作废
              </a>
              <a @click="handleDetail(scope?.record as SalesDetailModel)">
                查看详情
              </a>
              <a @click="handleEdit(scope?.record as SalesDetailModel)">
                编辑
              </a>
              <a c-error @click="handleUpdate(scope?.record as SalesDetailModel)">
                一键更新
              </a>
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'salesStatus'">
            <div gap-2>
              {{ salesStatusMap[scope?.record?.salesStatus as keyof typeof salesStatusMap] as string }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'salesType'">
            <div gap-2>
              {{ salesTypeMap[scope?.record?.salesType as keyof typeof salesTypeMap] as string }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'salesCreateTime'">
            <div gap-2>
              {{ onCreateTimeChange(scope?.record.salesCreateTime) }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'salesPureProfit'">
            <div gap-2>
              <span :style="{ color: scope?.record?.salesPureProfit > 0 ? 'rgb(0, 128, 0)' : 'red' }">
                {{ scope?.record?.salesPureProfit }} 元
              </span>
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'salesTotal'">
            <div gap-2>
              {{ formatDifference(scope?.record?.salesTotalPrice, scope?.record?.salesActualTotalPrice) }} 元
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
    <SalesAdd ref="salesAdd" />
    <SalesDetail ref="salesDetail" />
  </page-container>
</template>
